package com.aaxis.microservice.training.demo1.security;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    private Logger log = LoggerFactory.getLogger(getClass());

    @Value("${sys.contextPrefix:}")
    private String contextPrefix;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        log.debug("访问uri: {0} 权限不足：{1}",request.getRequestURI(),accessDeniedException.getMessage());
        String url = "/accessDenied";
        if(StringUtils.isNotBlank(contextPrefix)){
            url = contextPrefix.startsWith("/") ? contextPrefix+url : "/"+contextPrefix+url;
        }
        response.sendRedirect(url);
    }
}
